package com.caiying.dota.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.caiying.dota.domain.User;
import com.caiying.dota.service.UserService;

@Service @Transactional
public class UserServiceBean implements UserService{
	@Resource SessionFactory sessionFactory; 
	
	@Override
	public boolean save(User user) {
		if(get(user.getUsername()) == null){
			sessionFactory.getCurrentSession().save(user);
		} else {
			return false;
		}
		return true;
	}

	@Override
	public void update(User user) {
		sessionFactory.getCurrentSession().merge(user);
		
	}
	
	@Override
	public void delete(String... usernames) {
		for(String username : usernames){
			sessionFactory.getCurrentSession().delete(sessionFactory.getCurrentSession().get(User.class, username));
		}
		
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	@Override
	public User get(String username) {
//		return (User) sessionFactory.getCurrentSession().get(User.class, id);
		Query query = sessionFactory.getCurrentSession().createQuery("from User u where u.username = '"+username +"'");
		User user = null;
		if(query.list() != null && query.list().size() != 0){
			user = (User) query.list().get(0);
		}
		return user;
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	@SuppressWarnings("unchecked")
	@Override
	public List<User> list() {
		return sessionFactory.getCurrentSession().createQuery("from User").list();
	}

}
